var express = require('express');
var app = express();

var mongo = require('mongodb');
var request = require('request');
var YUI = require('yui').YUI;

var host = process.env['DOTCLOUD_DB_MONGODB_HOST'] || 'localhost';
var port = process.env['DOTCLOUD_DB_MONGODB_PORT'] ||  27017;
port = parseInt(port);
var user = process.env['DOTCLOUD_DB_MONGODB_LOGIN'] || undefined;
var pass = process.env['DOTCLOUD_DB_MONGODB_PASSWORD'] || undefined;

var mongoServer = new mongo.Server(host, port, {});
var db = new mongo.Db("test", mongoServer, {auto_reconnect:true});

app.get("/", function(req, res){
    var html = "";
	html+="<div id='demo'>";
	html+="<div id='container'>";
	html+="<p>Click for Hello World test.</p>";
	html+="</div>";
	html+="<p><a href='http://yuilibrary.com' id='firstA'>The YUI Library. (Link navigates away from page.)</a></p>";
	html+="<a href='http://yuilibrary.com' id='secondA'>The YUI Library. (Links default behavior is suppressed.)</a>";
	html+="<div class='message'>";
	html+="When you clicked on the second link, *preventDefault* was called, so it did not navigate away from the page.";
	html+="</div>";
	html+="</div>";
    html += "Hello World, from 'www.appfog.com'";

	YUI().use('node', function (Y) {
    	// A function that gives hello world feedback:
    	var helloWorld = function(e) {
        	e.target.setHTML("<p>Hello World!</p>");
        	Y.one('#container').addClass('hello');
    	}

    	// subscribe the helloWorld function as an event handler for the click
    	// event on the container div:
    	var node = Y.one("#container");

    	node.on("click", helloWorld);

    	// A function that displays a message and prevents the default behavior of
    	// the event for which it is a handler:
    	var interceptLink = function(e) {
        	e.preventDefault();
        	Y.one('.message').setStyle('visibility', 'visible');
    	}

    	// subscribe our interceptLink function as a click handler for the second
    	// anchor element:
    	Y.one('#secondA').on("click", interceptLink);
	});

    db.collection("test", function(err, collection){
        if(err) console.log(err);
        collection.find(function(err, cursor){
            if(err) console.log(err);
            res.send(html);
        });
    })
});

db.open(function(err){
    if(err) console.log(err);

    if(user && pass) {
        db.authenticate(user, pass, function(err) {
            app.listen(8080);
        });
    }
    else {
        app.listen(8080);
    }
});
